Skip to main content

Time counter

How to create a time counter simply and efficiently in Java

In your Java class, do the following:

public class YourClass extends Component {

// This variable will be responsible for storing the time that the counter will need to reach to execute something
public float maxTime = 5f; // change the value by properties

// the time counter
private float counter;

// variable for example purposes only
private int value = 1;

@Override
public void start() {

}

@Override
public void repeat() {

// we add the counter with "Math.bySecond()" so that every second it has its value increased by 1
counter += Math.bySecond();

// we check if the counter has reached the maximum time defined in the variable "maxTime"
if (counter >= maxTime) {

// resetting the counter
counter = 0f;

// The method will be called whenever the counter reaches the maximum time
myMethod(value);

}

}

// method for example purposes only
private int myMethod(int value) {

// returns the value of the variable "value" + 1
return value + 1;
}

}